package dev.werillib.utils

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

/**
 * create by weril 2018/12/19
 */
fun EditText.addDecimalListener(decimalListener: DecimalListener? = null) {
    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            var text = text.toString().trim()

            if (text.startsWith("00")) {
                text = text.substring(0, text.length - 1)
                setText(text)
                setSelection(text.length)
            }

            if (text.contains(".")) {
                val a = text.split(".")
                if (a.size == 2 && a[1].length > 2) {
                    text = text.substring(0, text.length - 1)
                    setText(text)
                    setSelection(text.length)
                }
            }
            decimalListener?.getText(text)
        }

        override fun beforeTextChanged(
            s: CharSequence?,
            start: Int,
            count: Int,
            after: Int
        ) {
        }

        override fun onTextChanged(
            s: CharSequence?,
            start: Int,
            before: Int,
            count: Int
        ) {
        }
    })
}

interface DecimalListener {
    fun getText(text: String)
}